import { useState, useEffect } from 'react'
import { Plus, Trash2, Play, Settings, Info } from 'lucide-react'
import { toast } from 'react-hot-toast'
import type { FieldConfig, DataGeneratorConfig, FieldType } from '@/types/dataGenerator'
import { dataGeneratorApi } from '@/services/dataGenerator'

interface DataGeneratorFormProps {
  topics: string[]
  onStartGeneration: (config: DataGeneratorConfig) => void
}

export default function DataGeneratorForm({ topics, onStartGeneration }: DataGeneratorFormProps) {
  const [config, setConfig] = useState<DataGeneratorConfig>({
    topic: '',
    fields: [
      { name: 'id', type: 'uuid', options: {} },
      { name: 'name', type: 'name', options: {} },
      { name: 'email', type: 'email', options: {} },
      { name: 'created_at', type: 'datetime', options: { current: true } }
    ],
    count: 100,
    interval: 1.0,
    batch_size: 1,
    stream_mode: true
  })

  const [fieldTypes, setFieldTypes] = useState<FieldType[]>([])
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    loadFieldTypes()
  }, [])

  const loadFieldTypes = async () => {
    try {
      const response = await dataGeneratorApi.getFieldTypes()
      setFieldTypes(response.field_types)
    } catch (error) {
      console.error('加载字段类型失败:', error)
      toast.error('加载字段类型失败')
    }
  }

  const addField = () => {
    setConfig(prev => ({
      ...prev,
      fields: [...prev.fields, { name: '', type: 'string', options: {} }]
    }))
  }

  const removeField = (index: number) => {
    setConfig(prev => ({
      ...prev,
      fields: prev.fields.filter((_, i) => i !== index)
    }))
  }

  const updateField = (index: number, field: Partial<FieldConfig>) => {
    setConfig(prev => ({
      ...prev,
      fields: prev.fields.map((f, i) => i === index ? { ...f, ...field } : f)
    }))
  }

  const updateFieldOption = (fieldIndex: number, optionKey: string, optionValue: any) => {
    setConfig(prev => ({
      ...prev,
      fields: prev.fields.map((f, i) => 
        i === fieldIndex 
          ? { ...f, options: { ...f.options, [optionKey]: optionValue } }
          : f
      )
    }))
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    if (!config.topic) {
      toast.error('请选择Topic')
      return
    }

    if (config.fields.length === 0) {
      toast.error('请至少添加一个字段')
      return
    }

    // 验证字段名称
    const fieldNames = config.fields.map(f => f.name)
    const duplicateNames = fieldNames.filter((name, index) => fieldNames.indexOf(name) !== index)
    if (duplicateNames.length > 0) {
      toast.error(`字段名称重复: ${duplicateNames.join(', ')}`)
      return
    }

    const emptyNames = config.fields.filter(f => !f.name.trim())
    if (emptyNames.length > 0) {
      toast.error('请填写所有字段名称')
      return
    }

    setLoading(true)
    try {
      onStartGeneration(config)
      toast.success('数据生成任务已启动')
    } catch (error) {
      console.error('启动生成任务失败:', error)
      toast.error('启动生成任务失败')
    } finally {
      setLoading(false)
    }
  }

  const renderFieldOptions = (field: FieldConfig, fieldIndex: number) => {
    const fieldType = fieldTypes.find(ft => ft.type === field.type)
    if (!fieldType || Object.keys(fieldType.options).length === 0) {
      return null
    }

    return (
      <div className="mt-2 p-3 bg-gray-50 rounded border">
        <div className="text-xs font-medium text-gray-600 mb-2">字段选项:</div>
        <div className="grid grid-cols-2 gap-2">
          {Object.entries(fieldType.options).map(([optionKey, optionDesc]) => (
            <div key={optionKey}>
              <label className="block text-xs text-gray-600 mb-1">{optionDesc}</label>
              {optionKey === 'values' ? (
                <textarea
                  className="w-full px-2 py-1 text-xs border rounded"
                  placeholder="用逗号分隔多个值"
                  value={field.options?.[optionKey] ? field.options[optionKey].join(',') : ''}
                  onChange={(e) => {
                    const values = e.target.value.split(',').map(v => v.trim()).filter(v => v)
                    updateFieldOption(fieldIndex, optionKey, values)
                  }}
                />
              ) : optionKey.includes('date') ? (
                <input
                  type="datetime-local"
                  className="w-full px-2 py-1 text-xs border rounded"
                  value={field.options?.[optionKey] || ''}
                  onChange={(e) => updateFieldOption(fieldIndex, optionKey, e.target.value)}
                />
              ) : optionKey === 'current' ? (
                <input
                  type="checkbox"
                  checked={field.options?.[optionKey] || false}
                  onChange={(e) => updateFieldOption(fieldIndex, optionKey, e.target.checked)}
                />
              ) : (
                <input
                  type={optionKey.includes('min') || optionKey.includes('max') || optionKey === 'precision' ? 'number' : 'text'}
                  className="w-full px-2 py-1 text-xs border rounded"
                  placeholder={optionDesc}
                  value={field.options?.[optionKey] || ''}
                  onChange={(e) => {
                    const value = e.target.type === 'number' ? Number(e.target.value) : e.target.value
                    updateFieldOption(fieldIndex, optionKey, value)
                  }}
                />
              )}
            </div>
          ))}
        </div>
      </div>
    )
  }

  return (
    <div className="bg-white rounded-lg shadow-sm border p-6">
      <div className="flex items-center space-x-2 mb-6">
        <Settings className="w-5 h-5 text-blue-600" />
        <h2 className="text-lg font-semibold text-gray-900">数据生成配置</h2>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6">
        {/* 基本配置 */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              目标Topic *
            </label>
            <select
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              value={config.topic}
              onChange={(e) => setConfig(prev => ({ ...prev, topic: e.target.value }))}
              required
            >
              <option value="">选择Topic</option>
              {topics.map(topic => (
                <option key={topic} value={topic}>{topic}</option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              生成数量
            </label>
            <input
              type="number"
              min="1"
              max="100000"
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              value={config.count}
              onChange={(e) => setConfig(prev => ({ ...prev, count: Number(e.target.value) }))}
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              发送间隔(秒)
            </label>
            <input
              type="number"
              min="0.1"
              max="60"
              step="0.1"
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              value={config.interval}
              onChange={(e) => setConfig(prev => ({ ...prev, interval: Number(e.target.value) }))}
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              批次大小
            </label>
            <input
              type="number"
              min="1"
              max="1000"
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              value={config.batch_size}
              onChange={(e) => setConfig(prev => ({ ...prev, batch_size: Number(e.target.value) }))}
            />
          </div>
        </div>

        {/* 流式发送选项 */}
        <div className="flex items-center space-x-2">
          <input
            type="checkbox"
            id="stream_mode"
            checked={config.stream_mode}
            onChange={(e) => setConfig(prev => ({ ...prev, stream_mode: e.target.checked }))}
            className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
          />
          <label htmlFor="stream_mode" className="text-sm text-gray-700">
            流式发送 (按间隔逐条发送，否则批量发送)
          </label>
        </div>

        {/* 字段配置 */}
        <div>
          <div className="flex items-center justify-between mb-3">
            <label className="block text-sm font-medium text-gray-700">
              字段配置 *
            </label>
            <button
              type="button"
              onClick={addField}
              className="flex items-center space-x-1 px-3 py-1 text-sm bg-blue-600 text-white rounded hover:bg-blue-700"
            >
              <Plus className="w-4 h-4" />
              <span>添加字段</span>
            </button>
          </div>

          <div className="space-y-3">
            {config.fields.map((field, index) => (
              <div key={index} className="border border-gray-200 rounded-lg p-4">
                <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                  <div>
                    <label className="block text-xs font-medium text-gray-600 mb-1">字段名称</label>
                    <input
                      type="text"
                      className="w-full px-2 py-1 text-sm border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-500"
                      placeholder="字段名称"
                      value={field.name}
                      onChange={(e) => updateField(index, { name: e.target.value })}
                    />
                  </div>

                  <div>
                    <label className="block text-xs font-medium text-gray-600 mb-1">字段类型</label>
                    <select
                      className="w-full px-2 py-1 text-sm border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-500"
                      value={field.type}
                      onChange={(e) => updateField(index, { type: e.target.value, options: {} })}
                    >
                      {fieldTypes.map(ft => (
                        <option key={ft.type} value={ft.type}>
                          {ft.description} ({ft.type})
                        </option>
                      ))}
                    </select>
                  </div>

                  <div className="flex items-end">
                    <button
                      type="button"
                      onClick={() => removeField(index)}
                      className="flex items-center justify-center w-8 h-8 text-red-600 hover:bg-red-50 rounded"
                      title="删除字段"
                    >
                      <Trash2 className="w-4 h-4" />
                    </button>
                  </div>
                </div>

                {renderFieldOptions(field, index)}
              </div>
            ))}
          </div>
        </div>

        {/* 提交按钮 */}
        <div className="flex items-center justify-between pt-4 border-t">
          <div className="flex items-center space-x-1 text-sm text-gray-500">
            <Info className="w-4 h-4" />
            <span>生成的数据将包含 _generated_at 和 _generator_id 元数据字段</span>
          </div>
          
          <button
            type="submit"
            disabled={loading}
            className="flex items-center space-x-2 px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <Play className="w-4 h-4" />
            <span>{loading ? '启动中...' : '开始生成'}</span>
          </button>
        </div>
      </form>
    </div>
  )
}
